package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"goMicro/day06/sidecar"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

//一个普通的外部服务,注册到服务中心
func main() {
	ginRouter := gin.Default()
	v1 := ginRouter.Group("/v1")
	{
		v1.Handle("post", "/test", func(ctx *gin.Context) {
			ctx.JSON(200, gin.H{"data": "test"})
		})

	}
	server := &http.Server{
		Addr:              ":8088",
		Handler:           ginRouter,
		TLSConfig:         nil,
		ReadTimeout:       0,
		ReadHeaderTimeout: 0,
		WriteTimeout:      0,
		IdleTimeout:       0,
		MaxHeaderBytes:    0,
		TLSNextProto:      nil,
		ConnState:         nil,
		ErrorLog:          nil,
		BaseContext:       nil,
		ConnContext:       nil,
	}
	//这里创建外部服务
	ser := sidecar.NewService("api.jtthink.com.test")
	ser.AddNode("test-"+uuid.New().String(), 8088, "127.0.0.1:8088")

	handler := make(chan error)
	go func() {
		handler <- server.ListenAndServe()
	}()

	go func() {
		notify := make(chan os.Signal)
		signal.Notify(notify, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
		handler <- fmt.Errorf("%s", <-notify)
	}()

	go func() {
		//注册服务
		if err := sidecar.RegService(ser); err != nil {
			handler <- err
		}
	}()
	getHandle := <-handler
	fmt.Println(getHandle.Error())
	//注销服务
	if err := sidecar.DeRegService(ser); err != nil {
		handler <- err
	}

	if err := server.Shutdown(context.Background()); err != nil {
		log.Fatal(err)
	}
}
